<template>
  <div class="container">
    <div class="title mb-4">规范录入</div>

    <!-- 查询表单 -->
    <div class="border-bottom">
      <el-form
        :model="formModel"
        ref="queryForm"
        label-width="100px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="版本" prop="version">
              <xcmg-select
                v-model="formModel.version"
                placeholder="请选择版本"
                clearable
                @change="handleSearch"
              >
                <xcmg-option
                  v-for="item in versionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </xcmg-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item>
              <xcmg-button stoke @click="handleSearch">查询</xcmg-button>
              <xcmg-button @click="resetForm" class="ml-2">重置</xcmg-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <xcmg-button  type="primary" @click="handleImport">
        <svg-icon name="upload-line" />
        <div class="spacer"></div>
        导入
      </xcmg-button>
      <xcmg-button @click="handleExport" :loading="downLoading">
        <svg-icon name="download-fill" />
        <div class="spacer"></div>
        导出
      </xcmg-button>
      <xcmg-button @click="handleRestoreLatest">
        <svg-icon name="refresh-line" />
        <div class="spacer"></div>
        恢复最新版本
      </xcmg-button>
      <xcmg-button @click="handleSaveDraft">
        <svg-icon name="archive" />
        <div class="spacer"></div>
        暂存
      </xcmg-button>
      <xcmg-button  @click="handlePublish">
        <svg-icon name="cloud" />
        <div class="spacer"></div>
        发布
      </xcmg-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <xcmg-table
        :data="tableData"
        v-loading="loading"
        height="100%"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="chineseName"
          label="中文名称"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="englishName"
          label="英文名称"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="aiBusinessPurpose"
          label="业务定义及用途-AI专有"
          width="160"
        />
        <el-table-column
          prop="dataType"
          label="数据类型"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="dataLength"
          label="数据长度"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="hasAllowedValues"
          label="是否有允许值"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <xcmg-tag :type="row.hasAllowedValues ? 'success' : 'danger'">
              {{ row.hasAllowedValues ? "是" : "否" }}
            </xcmg-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="supplementPurpose"
          label="业务定义及用途增补"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="supplementRule"
          label="业务规则增补"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="{ row }">
            <xcmg-button type="text" size="small" @click="editRow(row)"
              >业务定义增补编辑</xcmg-button
            >
            <xcmg-button type="text" size="small" @click="editRow(row)"
              >业务规则增补编辑</xcmg-button
            >
            <!-- <xcmg-button type="text" size="small" @click="deleteRow(row)">删除</xcmg-button> -->
          </template>
        </el-table-column>
      </xcmg-table>
      <!-- 分页 -->
      <div class="fixed-pagination">
        <xcmg-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 50, 100, 200, 500]"
          :total="total"
          background
          layout="total,sizes,prev, pager, next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
  <Edit v-model:visible="visible" title="编辑"/>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { XcmgMessageBox, XcmgMessage } from "xcmg-components";
import { useToggle } from "@/hooks/useToggle";
import { SvgIcon } from 'xcmg-components'
import Edit from "./components/edit.vue";
// import {
//   materialRuleList,
//   materialRuleInfo,
//   materialRuleDelete,
// } from "@/api/ruleBase";

// 模拟数据
const mockTableData: TableItem[] = [
  {
    id: 1,
    uid: "M00000001",
    chineseName: "物料编码",
    englishName: "Material Code",
    aiBusinessPurpose: "唯一标识物料，AI用于自动匹配BOM",
    dataType: "字符串",
    dataLength: "20",
    hasAllowedValues: true,
    supplementPurpose: "支持条码扫描识别",
    supplementRule: "必须以M开头，后接8位数字",
  },
  {
    id: 2,
    uid: "M00000002",
    chineseName: "物料名称",
    englishName: "Material Name",
    aiBusinessPurpose: "用于自然语言搜索和描述生成",
    dataType: "字符串",
    dataLength: "100",
    hasAllowedValues: false,
    supplementPurpose: "允许中英文混合输入",
    supplementRule: "禁止特殊字符（如@#$%）",
  },
  {
    id: 3,
    uid: "M00000003",
    chineseName: "单位重量",
    englishName: "Unit Weight",
    aiBusinessPurpose: "AI预测物流成本的基础参数",
    dataType: "数值",
    dataLength: "10,3",
    hasAllowedValues: true,
    supplementPurpose: "精度保留三位小数",
    supplementRule: "范围：0.001 ~ 999.999",
  },
  {
    id: 4,
    uid: "M00000004",
    chineseName: "颜色分类",
    englishName: "Color Category",
    aiBusinessPurpose: "图像识别训练标签之一",
    dataType: "枚举",
    dataLength: null,
    hasAllowedValues: true,
    supplementPurpose: "仅限系统预设颜色值",
    supplementRule: "红/蓝/黑/白/灰",
  },
  {
    id: 5,
    uid: "M00000005",
    chineseName: "是否环保",
    englishName: "Is Eco-Friendly",
    aiBusinessPurpose: "绿色供应链评估维度",
    dataType: "布尔",
    dataLength: null,
    hasAllowedValues: true,
    supplementPurpose: "需提供第三方认证",
    supplementRule: "默认为否，需手动确认开启",
  },
];

interface TableItem {
  id: number;
  uid: string; // 假设有唯一标识
  chineseName: string;
  englishName: string;
  aiBusinessPurpose: string;
  dataType: string;
  dataLength: string | null;
  hasAllowedValues: boolean;
  supplementPurpose: string;
  supplementRule: string;
}

// 表单引用
const queryForm = ref<FormInstance>();

// 表单数据
const formModel = reactive({
  version: "",
});

// 下拉选项
const versionOptions = ref<{ label: string; value: string }[]>([
  { label: "V1.0", value: "1" },
  { label: "V2.0", value: "2" },
  { label: "V3.0", value: "3" },
]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const downLoading = ref(false);
const selectedRows = ref<TableItem[]>([]);
const title = ref<string>("");
const rowData = ref<Partial<TableItem> | null>(null);
const [visible, editVisible] = useToggle();

// 获取表格数据
// const fetchTableData = async () => {
//   try {
//     loading.value = true;
//     const params = {
//       pageNo: currentPage.value,
//       pageSize: pageSize.value,
//       query: {
//         version: formModel.version || undefined,
//       },
//     };
//     const res = await materialRuleList(params);
//     tableData.value = res.data || [];
//     total.value = res.total || 0;
//   } catch (error) {
//     console.error("获取数据失败:", error);
//     XcmgMessage({ message: "数据加载失败", type: "error" });
//     tableData.value = [];
//     total.value = 0;
//   } finally {
//     loading.value = false;
//   }
// };

// 获取表格数据 - 使用本地 mock 数据
const fetchTableData = async () => {
  try {
    loading.value = true;

    // 模拟异步请求延迟
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 简单分页逻辑
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;

    // 模拟版本过滤（可选）
    let filteredData = mockTableData;
    if (formModel.version) {
      // 可以扩展为按版本过滤字段，这里简单示意
      console.log("筛选版本:", formModel.version);
    }

    tableData.value = filteredData.slice(start, end);
    total.value = filteredData.length;
  } catch (error) {
    console.error("获取数据失败:", error);
    XcmgMessage({ message: "数据加载失败", type: "error" });
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 查询 & 重置
const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};

const resetForm = () => {
  if (queryForm.value) {
    queryForm.value.resetFields();
  }
  handleSearch();
};

// 分页事件
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchTableData();
};

// 行选择
const handleSelectionChange = (rows: TableItem[]) => {
  selectedRows.value = rows;
};

// 按钮事件
const handleImport = () => {
  // TODO: 导入逻辑
  console.log("导入");
};

const handleExport = async () => {
  downLoading.value = true;
  try {
    // TODO: 导出逻辑
    await new Promise((resolve) => setTimeout(resolve, 1000));
    XcmgMessage({ message: "导出成功", type: "success" });
  } finally {
    downLoading.value = false;
  }
};

const handleRestoreLatest = () => {
  XcmgMessageBox.confirm("确定恢复到最新版本？", "提示", {
    type: "info",
    draggable: true,
  })
    .then(() => {
      fetchTableData(); // 示例：刷新数据
      XcmgMessage({ message: "已恢复最新版本", type: "success" });
    })
    .catch(() => {});
};

const handleSaveDraft = () => {
  XcmgMessage({ message: "暂存成功", type: "info", plain: true });
};

const handlePublish = () => {
  XcmgMessageBox.confirm("确定发布当前版本？", "发布确认", {
    type: "warning",
    confirmButtonText: "发布",
    cancelButtonText: "取消",
  }).then(() => {
    XcmgMessage({ message: "发布成功", type: "success" });
  });
};

// 编辑
const editRow = async (row: TableItem) => {
  title.value = "编辑";
  editVisible();
};

// // 编辑
// const editRow = async (row: TableItem) => {
//   try {
//     const res = await materialRuleInfo({ uid: row.uid });
//     rowData.value = res.data;
//     title.value = "编辑";
//     newBuiltVisible();
//   } catch (error) {
//     XcmgMessage({ message: "获取详情失败", type: "error" });
//   }
// };

// 删除
// const deleteRow = (row: TableItem) => {
//   XcmgMessageBox.confirm("此操作将永久删除该数据，是否继续？", "警告", {
//     confirmButtonText: "确定",
//     cancelButtonText: "取消",
//     type: "warning",
//     customClass: "xcmg-message-box--warning",
//   })
//     .then(async () => {
//       await materialRuleDelete({ uid: row.uid });
//       XcmgMessage({ message: "删除成功", type: "success", showClose: true });
//       fetchTableData();
//     })
//     .catch(() => {});
// };

// 初始化
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
.container {
  padding: 20px;
  height: calc(100vh - 64px - 56px - 40px);
  display: flex;
  flex-direction: column;
}

.title {
  font-weight: bold;
  font-size: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.border-bottom {
  border-bottom: 1px solid #e5e7eb;
}

.button-group {
  padding: 16px 0;
  display: flex;
  gap: 12px;
}

.spacer {
  width: 8px;
}

/* 表格容器：占据剩余空间 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
/* 表格：允许滚动，限制最大高度 */

.fixed-pagination {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
  z-index: 1;
}

:deep(.el-form-item__content) {
    justify-content: flex-end;
}
</style>
